  #include <stdint.h>
  #define DELTA 0x9e3779b9
  #define MX (((z>>5^y<<2) + (y>>3^z<<4)) ^ ((sum^y) + (key[(p&3)^e] ^ z)))
 
  void btea(uint32_t *v, int n, uint32_t const key[4]) {
    uint32_t y, z, sum;
    unsigned p, rounds, e;
    if (n > 1) {          /* Coding Part */
      rounds = 6 + 52/n;
      sum = 0;
      z = v[n-1];
      do {
        sum += DELTA;
        e = (sum >> 2) & 3;
        for (p=0; p<n-1; p++) {
          y = v[p+1]; 
          z = v[p] += MX;
        }
        y = v[0];
        z = v[n-1] += MX;
      } while (--rounds);
    } else if (n < -1) {  /* Decoding Part */
      n = -n;
      rounds = 6 + 52/n;
      sum = rounds*DELTA;
      y = v[0];
      do {
        e = (sum >> 2) & 3;
        for (p=n-1; p>0; p--) {
          z = v[p-1];
          y = v[p] -= MX;
        }
        z = v[n-1];
        y = v[0] -= MX;
      } while ((sum -= DELTA) != 0);
    }
  }


char *toHexStr(uint8_t *bytes, int sz)
{
//  #define hexDigit(d) ( ((d)<10)?(d)+'0':(d)-10+'A' )
  #define hexDigit(d) hexDigits[d]
  char hexDigits[] = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};

  char *newBuf = (char *)malloc(sz*2+1);
  if(!newBuf) return 0;
  newBuf[sz*2] = 0;

  int i;
  for(i=0; i<sz; i++) {
    newBuf[i*2] = hexDigit(bytes[i]>>4);
    newBuf[i*2+1] = hexDigit(bytes[i]&0x0F);
  }

  return newBuf;
}

uint8_t *fromHexStr(char *hexStr)
{
  #define fromHexDigit(d) ( ((d)<'A')?(d)-'0':(d)-'A'+10 )

  int sz = strlen(hexStr);
  uint8_t *newBuf = (uint8_t *)malloc(sz/2);
  if(!newBuf) return 0;

  int i;
  for(i=0; i<sz/2; i++) {
    newBuf[i] = fromHexDigit(hexStr[2*i])<<4 | fromHexDigit(hexStr[2*i+1]);
  }

  return newBuf;
}

uint32_t key[4] = {'C','A','D','U'};
char *encStr(char *msg)
{
  char *result = 0;
  int sz = strlen(msg)+1;
  uint8_t *newMsg;
  int newSz;

  if(sz<8) newSz = 8;
  else if(sz&3) newSz = (sz & ~3) + 4;
  else newSz = sz;

  newMsg = (uint8_t *)malloc(newSz);
  if(!newMsg) return 0;

  memset(newMsg,0,newSz);
  memcpy(newMsg,msg,sz);

  btea((uint32_t *)newMsg,newSz/4,key);
  result = toHexStr(newMsg,newSz);

  free(newMsg);

  return result;
}

char *decStr(char *msg)
{
  int sz = strlen(msg)/2;
  uint8_t *newMsg = fromHexStr(msg);

  if(!newMsg) return 0;

  btea((uint32_t *)newMsg,-sz/4,key);

  return (char *)newMsg;
}

void main(void)
{
/*
  char message[12] = "teste123";

  btea(message,2,key);
  printf("cripted %s\n",message);

  btea(message,-2,key);
  printf("decripted %s\n",message);
*/
  char message[] = "testando 123 ouxe massa :) funciona";

  char *enc = encStr(message);
  printf("ENC HEX %s\n",enc);
  char *dec = decStr(enc);
  printf("DEC HEX %s\n",dec);
}
